package com.cyx.controller;

import com.cyx.dao.EmployeeDao;
import com.cyx.pojo.Employee;
import org.omg.CORBA.INTERNAL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/employee")
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @GetMapping("/list")
    public String list(Model model){
        model.addAttribute("employees",employeeDao.getEmployees());
        return "/employee/list";
    }

    @GetMapping("/add")
    public String add(Model model){
        model.addAttribute("departments",employeeDao.getDepartments());
        return "/employee/add";
    }

    @PostMapping("/add")
    public String add(Employee employee){
        System.out.println(employee);
        employeeDao.saveEmployee(employee);
        return "redirect:/employee/list";
    }

    @GetMapping("/{id}")
    public String update(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.getEmployee(id);
        model.addAttribute("employee",employee);
        model.addAttribute("departments",employeeDao.getDepartments());
        return "/employee/edit";
    }

    @PostMapping("/{id}")
    public String update(@PathVariable("id") Integer id,Employee employee) {
        System.out.println(employee);
        employeeDao.updateEmployee(employee);
        return "redirect:/employee/list";
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id){
        employeeDao.deleteEmployee(id);
        return "redirect:/employee/list";
    }
}
